<template>
  <div class="data-manage">
    <div class="data-manage-opt">
      <div class="data-manage-search">
        <el-form
            label-width="80px"
            size="small"
            :inline="true"
        >
          <el-form-item label="检索属性">
            <el-select
                style="width: 225px"
                v-model="SearchForm.field" clearable placeholder="请选择">
              <el-option
                  v-for="item in Fields"
                  :key="item.name"
                  :label="item.Alias"
                  :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检索值">
            <el-input
                @input="handleCardSwipe"
                v-model="SearchForm.value"
                placeholder="请输入内容"
                clearable
            />
          </el-form-item>
          <el-form-item v-permission="CurrentTableName.name+'::find'" style="display: inline-block !important;">
            <el-button type="primary" round @click="SearchBtn">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="IsAuthentication" style="display: flex">
        <el-button
            size="small"
            v-permission="CurrentTableName.name+'::configTableHeader'"
            type="primary"
            @click="RenameAliasBtn"
        >配置表头
        </el-button>
        <el-button size="small" v-permission="CurrentTableName.name+'::add'" type="primary"
                   @click="AddTableDataBtn">
          新增
        </el-button>
      </div>
    </div>
    <div class="data-manage-table">
      <div>
        <el-menu
            default-active="1"
            class="el-menu-vertical-demo"
        >
          <el-menu-item
              @click="SelectTableData(item,ind)"
              class="data-manage-table-item"
              :index="item.name"
              v-for="(item,ind) in TableNames"
              :key="ind"
          >
            <i class="el-icon-menu"></i>
            <template #title>
              <span>{{ item.TableAlias }}</span>
            </template>
          </el-menu-item>
        </el-menu>
      </div>
      <div style="width: 90%;">
        <!--        其他表格内容元素-->
        <el-table
            border
            :data="TableData"
            style="width: 100%;user-select: text"
        >
          <template v-for="(Field,index) in Fields" :key="index">
            <el-table-column
                :width="Field.Column ==='create_time'?'150px':''"
                :prop="Field.name"
                :label="Field.Alias"
                align="center"
            >
            </el-table-column>
          </template>
          <el-table-column
              label="操作"
              fixed="right"
              width="135"
              v-if="isShowOperation"
              class-name="optioner-cell"
          >
            <template #default="scope">
              <el-button
                  @click="OnDelete(scope.row)"
                  v-permission="CurrentTableName.name+'::delete'"
                  type="text"
                  size="small"
              >删除
              </el-button>
              <el-button
                  @click="OnEdit(scope.row)"
                  v-permission="CurrentTableName.name+'::edit'"
                  type="text"
                  size="small"
                  :data-userid="scope.row.id"
                  :data-role="scope.row.role"
              >编辑
              </el-button>
              <el-button
                  @click="ConfigUserPermissions(scope.row)"
                  type="text"
                  size="small"
                  v-permission="CurrentTableName.name+'::auth'"
                  v-if="CurrentTableName.name==='business_user'"
              >权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 6px">
          <el-pagination
              @current-change="HandleCurrentChange"
              :current-page="CurrentPage"
              layout="total, prev, pager, next, jumper"
              :total="Total"
              :page-size="Size"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
        append-to-body
        :close-on-click-modal="false"
        :title="'编辑数据：'+CurrentTableName.TableAlias"
        custom-class="app-event-dialog us-none"
        v-model="ShowAddTableDataDialog"
        width="30%"
        top="15vh"
    >
      <el-form ref="form" label-width="125px" size="mini">
        <el-form-item
            :label="field.Alias"
            v-for="(field,index) in Fields"
            :key="index"
            v-show="field?.pk !==1&&field.name !='create_time'&&field.name != 'create_user'"
        >
          <template v-if="CurrentTableName.name+field.name==='business_userrole'">
            <el-select v-model="field.Value" :disabled="field.disabled||false" clearable placeholder="请选择用户角色"
                       style="width: 100%">
              <el-option
                  v-for="item in Roles"
                  :key="item.value"
                  :label="item.tip"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
          <el-input v-else :type="field.type" v-model="field.Value"></el-input>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end">
          <el-button type="primary" @click="onSave">保存</el-button>
          <el-button @click="ShowAddTableDataDialog=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
        append-to-body
        :close-on-click-modal="false"
        :title="'重命名：'+CurrentTableName.name"
        custom-class="app-event-dialog us-none"
        v-model="ShowRenameAliasDialog"
        width="30%"
        top="15vh"
    >
      <el-form ref="form" label-width="125px" size="mini">
        <el-form-item label="表别名">
          <el-input v-model="TableAlias"></el-input>
        </el-form-item>
        <el-form-item
            :label="field.name"
            v-for="(field,index) in Fields"
            :key="index"
            v-show="field.pk !==1"
        >
          <!--          {{ field }}-->
          <el-input v-model="field.Alias"></el-input>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end">
          <el-button type="primary" @click="onSaveRenameAlias">保存</el-button>
          <el-button @click="ShowRenameAliasDialog=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
        append-to-body
        :close-on-click-modal="false"
        title="分配权限"
        custom-class="app-event-dialog us-none"
        v-model="ShowUserPermissionsDialog"
        width="45%"
        top="18vh"
    >
      <user-permissions-dialog ref="UserPermissionsDialogRef"></user-permissions-dialog>
    </el-dialog>
    <!--    </el-dialog>-->
  </div>
</template>
<script>
import { DataManage } from '@/api/DataManageApi'
import SqlTool from '../../utils/SqlTool'
import Utils from '../../utils/Common'
import { AppParams } from '@/utils/appParams'
import UserPermissionsDialog from './UserPermissionDialog.vue'
import { MessageSuccess, MessageWarning, MessageError } from "@/utils";

export default {
  name: 'DataManage',
  components: { UserPermissionsDialog },
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    show (n, o) {
      if (n) {
        this.VisibleDataManageDialog = true
      }
    }
  },
  data () {
    return {
      VisibleDataManageDialog: false,
      SearchForm: {
        field: null,
        value: null,
        Where: null
      },
      TableNames: [],
      TableData: [],
      CurrentTableName: {},
      Roles: AppParams.COMMON.BUSINESS_USER_ROLE,
      Fields: [],
      CurrentPage: 1,
      Size: 12,
      Total: 0,
      TotalPage: 0,
      ShowAddTableDataDialog: false,
      ShowRenameAliasDialog: false,
      ShowUserPermissionsDialog: false,
      IsEdit: false,
      FieldMapping: {},
      TableAlias: null,
      IsAuthentication: Utils.IsAuthentication(),
      UserInfo: Utils.GetLoginUserInfo()
    }
  },
  computed: {
    isShowOperation () {
      if (!this.IsAuthentication) {
        return false
      }
      return !this.CurrentTableName?.name?.startsWith('production')
    }
  },
  methods: {
    handleCloseModal () {
      this.VisibleDataManageDialog = false
      this.$emit('close')
    },
    /**
     * 监听编辑事件
     * @param item
     * @param index
     * @constructor
     */
    OnEdit (item, index) {
      if (!this.IsAuthentication) {
        return MessageWarning('请登录后重试');
      }
      this.IsEdit = true
      this.ShowAddTableDataDialog = true
      for (const field of this.Fields) {
        field.disabled = false;
        for (const itemKey in item) {
          if (field.name === itemKey) {
            field.Value = item[itemKey]
          }
          // 不能自己编辑自己的角色
          if (this.CurrentTableName.name === 'business_user' && field.name === 'role' && item.id === UserInfoId) {
            field.disabled = true;
          }
        }
      }
    },
    /**
     * 监听删除事件
     * @param item
     * @param index
     * @constructor
     */
    OnDelete (item, index) {
      this.$confirm(`是否删除表${this.CurrentTableName.TableAlias}中的数据，id=${item.id}？`, `确认删除`, {
        distinguishCancelAndClose: true,
        roundButton: true,
        confirmButtonClass: 'el-button--warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(() => {
        const _SQL = SqlTool.GeneratedDeleteSql(this.CurrentTableName, 'id=' + item.id)
        DataManage.ExecuteSql(_SQL).then(res => {
          if (res.Data > 0) {
            this.AddSuccess()
            MessageSuccess('删除成功，受影响行数：' + res.Data)
          } else {
            MessageWarning('删除失败，受影响行数：' + res.Data)
          }
        })
      })
    },
    ConfigUserPermissions (item) {
      if (!Utils.IsAuthentication()) {
        return MessageError("登录后重试");
      }
      if (this.UserInfo.id === item.id) {
        return MessageWarning("无法给自己设置权限");
      }
      this.ShowUserPermissionsDialog = true
      this.$nextTick(() => {
        this.$refs.UserPermissionsDialogRef.LoadUserPermissions(item, this.TableNames)
      })
    },
    /**
     * 监听保存按钮事件
     */
    onSave () {
      let _SQL = SqlTool.GeneratedInsertSql(this.CurrentTableName, this.Fields)
      if (this.IsEdit) {
        _SQL = SqlTool.GeneratedUpdateSql(this.CurrentTableName, this.Fields)
      }
      DataManage.ExecuteSql(_SQL).then(res => {
        if (res?.Data > 0) {
          this.AddSuccess()
          MessageSuccess('保存成功，受影响行数：' + res.Data)
        } else {
          MessageWarning('保存失败，受影响行数：' + res.Data)
        }
      })
    },
    onSaveRenameAlias () {
      const TableName = 'sys_field_mapping'
      const TargetTableName = this.CurrentTableName.name
      const Values = []
      const AllSQL = []
      for (const datum of this.Fields) {
        if (datum.pk === 1) {
          continue
        }
        if (datum.MappingId) {
          const SetFields = []
          SetFields.push(`table_name = '${TargetTableName}'`)
          SetFields.push(`table_alias = '${this.TableAlias}'`)
          SetFields.push(`field_name = '${datum.name}'`)
          SetFields.push(`field_alias = '${datum.Alias}'`)
          AllSQL.push(SqlTool.UPDATE_SQL + TableName + ' set ' + SetFields.join(',') + ' WHERE id=' + datum.MappingId)
          continue
        }
        Values.push(`('${TargetTableName}','${this.TableAlias}','${datum.name}','${datum.Alias}')`)
      }
      if (!Utils.IsEmpty(Values)) {
        const _INSERT_SQL = SqlTool.INSERT_SQL + TableName + ' (table_name,table_alias,field_name,field_alias) VALUES ' + Values.join(',') + ';'
        AllSQL.push(_INSERT_SQL)
      }
      let UpdateNum = 0
      for (let i = 0; i < AllSQL.length; i++) {
        const allSQLElement = AllSQL[i]
        DataManage.ExecuteSql(allSQLElement).then(res => {
          if (res.Data > 0) {
            ++UpdateNum
          } else {
            MessageWarning('保存失败，受影响行数：' + res)
          }
          if (i === AllSQL.length - 1) {
            this.AddSuccess()
            MessageSuccess('保存成功，受影响行数：' + UpdateNum)
          }
        })
      }
    },
    AddSuccess () {
      for (const field of this.Fields) {
        field.Value = null
      }
      this.ShowAddTableDataDialog = false
      this.ShowRenameAliasDialog = false
      this.HandleCurrentChange()
    },
    AddTableDataBtn () {
      if (Utils.IsEmpty(this.CurrentTableName)) {
        return MessageWarning('请选择表，重新试试')
      }
      this.IsEdit = false
      this.ShowAddTableDataDialog = true
    },
    HandleCurrentChange (Page) {
      if (!Utils.IsEmpty(Page)) {
        this.CurrentPage = Page
      }
      this.extracted(this.CurrentTableName)
      // this.QueryData(SqlTool.GeneratedQuerySql(this.CurrentTableName.name, this.CurrentPage, this.Size, this.SearchForm.Where))
    },
    /**
     * 重命名表名和列名
     * @constructor
     */
    RenameAliasBtn () {
      if (Utils.IsEmpty(this.CurrentTableName)) {
        return MessageWarning('请选择表，重新试试')
      }
      this.ShowRenameAliasDialog = true
    },
    AddTable () {
    },
    extracted: function (item) {
      if (item.name === 'business_user') {
        const sqlfields = []
        for (const field of this.Fields) {
          if (field.name === 'role') {
            let append = ` case when role =5 then '管理员' `
            append += `  when role =4 then 'ME' `
            append += `  when role =3 then 'PE' `
            append += `  when role =2 then '技师' `
            append += `  when role =1 then '操作员' `
            append += ` else role `
            append += ` end as role `
            sqlfields.push(append)
          } else {
            sqlfields.push(field.name)
          }
        }
        this.QueryData(SqlTool.GeneratedQuerySql2('select ' + sqlfields.join(', ') + ' from business_user', this.CurrentPage, this.Size, this.SearchForm.Where))
      } else {
        this.QueryData(SqlTool.GeneratedQuerySql(this.CurrentTableName.name, this.CurrentPage, this.Size, this.SearchForm.Where))
      }
    },
    /**
     *
     * @constructor
     */
    SelectTableData (item, index) {
      this.CurrentTableName = item
      this.CurrentPage = 1
      this.SearchForm = {
        field: null,
        value: null,
        Where: null
      }
      this.TableAlias = item.TableAlias
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      DataManage.FindTableStructures(item.name).then(res => {
        this.Fields = res.Data
        for (const field of this.Fields) {
          if (field.type === 'INTEGER') {
            field.type = 'number'
          }
        }
        this.extracted(item)
      })
    },
    QueryData (Sql) {
      DataManage.PageBySql(Sql, this.CurrentTableName.name, this.CurrentPage, this.Size).then(res => {
        const _td = res.Data
        this.Total = _td.TotalCount
        this.TableData = _td.Data
        this.TotalPage = _td.TotalPage
      })
    },
    /**
     * 加载表格
     * @constructor
     */
    LoadTables () {
      DataManage.FindSystemDatabaseTableNames().then((res) => {
        this.TableNames = res.Data
      })
    },
    handleCardSwipe (v) {
    },
    /**
     * 查询表数据
     * @constructor
     */
    SearchBtn () {
      if (Utils.IsEmpty(this.CurrentTableName)) {
        MessageWarning('请先选择需要检索的表')
        return
      }
      const Search = this.SearchForm
      if (Utils.IsEmpty(Search.field) || Utils.IsEmpty(Search.value)) {
        this.SearchForm.Where = null
        this.HandleCurrentChange()
        return
      }
      this.SearchForm.Where = Search.field + '=\'' + Search.value + '\''
      this.HandleCurrentChange(1)
    }
  },
  mounted () {
    this.LoadTables()
  }
}
</script>

<style lang="less">

.data-manage-search {
  display: flex;
  margin-left: 140px;

  .el-form-item {
    margin-bottom: unset;
  }
}

.data-manage {
  .data-manage-opt {
    padding-bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;

    > div:nth-child(1) {
      //display: flex;
      //justify-content: end;
    }

  }

  .data-manage-table {
    display: flex;
    flex-direction: row;

    .optioner-cell {
      > div {
        display: flex;

        > button {
          padding: 0
        }
      }
    }

    .el-menu {
      width: 150px;
      border-right: unset;

      .data-manage-table-item {
        overflow: hidden;
        padding-left: 0 !important;

        .el-icon-menu {
          margin-right: 0;
        }
      }
    }
  }
}
</style>
